<?php

require_once dirname(__FILE__) . '/simple_html_dom.php';

class Editor_Controller
{
	const FILENAME_BASE = 'file_base.inf';
	static public function createHtml($jquery='',$form='')
	{
		$contents = 'empty';
		if (isset($_REQUEST['editor1'])){
			$contents = $_REQUEST['editor1'];
		}
		$title = 'notitle';
		if (!empty($_REQUEST['pagetitle'])) {
			$title = $_REQUEST['pagetitle'];
		}
		$html = file_get_contents(dirname(__FILE__).'/modify.tpl');
		$html = str_replace('{?TITLE?}', $title, $html);
		$html = str_replace('{?JQUERY?}', $jquery, $html);
		$html = str_replace('{?CONTENTS?}', $contents, $html);
		$html = str_replace('{?BODY_CONTROLLER?}', $form, $html);
		return $html;
	}
	
	static public function fetchMarty($aryKeyValues, $source)
	{
		foreach($aryKeyValues as $key=>$value) {
			$source = str_replace($key, $value, $source);
		}
		return $source;
	}
	
	static public function createFileName()
	{
		$baseFileName = dirname(__FILE__) .'/'.self::FILENAME_BASE;
		$fileNum = 0;
		if (file_exists($baseFileName)) {
			$fileNum = file_get_contents($baseFileName);
		}
		$fileNum ++;
		$htmlFileName = sprintf('%04x.html', $fileNum);
		file_put_contents($baseFileName, $fileNum);
		return $htmlFileName;
	}
	
	static public function setAllowEdit()
	{
		if (!isset($_SESSION)) {
			session_start();
		}
		$_SESSION['edit'] = 'OK';
	}
	
	static public function isAllowEdit()
	{
		if (!isset($_SESSION)) {
			session_start();
		}
		$result = FALSE;
		if (isset($_SESSION['edit'])) {
			if ($_SESSION['edit'] == 'OK') {
				$result = TRUE;
			}
		}
		return $result;
	}
	
	static function getFromBodyToBody2($htmlFile)
	{
		$html = file_get_html($htmlFile);
		$result = $html->find('body');
		$aryResult = array();
		foreach($result as $list) {
			$aryResult[] = $list->innertext;
		}
		return $aryResult[0];
	}
	
	static function getFromBodyToBody($htmlFile)
	{
		$html = file($htmlFile, FILE_IGNORE_NEW_LINES);
		$lineCount = count($html);
		$i = 0;
		while ($i < $lineCount) {
			if (trim($html[$i]) == '<body>') {
				break;
			}
			$i ++;
		}
		$aryResult = array();
		$i ++;
		while ($i < $lineCount) {
			if (trim($html[$i] == '</body>')) {
				break;
			}
			$aryResult[] = $html[$i];
			$i ++;
		}
		$sResult = implode("\n", $aryResult);
		return $sResult;
	}
	
	
	static function getTitleFromHtmlFile($htmlFile)
	{
		$html = file_get_html($htmlFile);
		$result = $html->find('title');
		$aryResult = array();
		foreach($result as $list) {
			$aryResult[] = $list->innertext;
		}
		return $aryResult[0];
	}
}

